import { reactive, watch, ref, Ref, toRefs, unref } from "vue";

type IQRef<T> = { [P in keyof T]?: Ref<T[P]> | T[P] };
export function useTable<
  R extends { list: any; total: number },
  P extends object
>(reqApi: (params: P) => RpI<R>, queryParams: IQRef<P>) {
  // let data = reactive({});
  let list = ref<R["list"]>([]);
  let params = {} as P;
  watch(
    () => queryParams,
    (val, oldval) => {
      for (let key in val) {
        params[key] = unref(val[key]) as P[Extract<keyof P, string>]; // p[keyword] | p[pageSize] | p[pageNum]
      }
    },
    { deep: true }
  );

  // 分页数据
  let paginate = reactive({
    currentPage: 1,
    pageSize: 10,
    small: true,
    total: 0,
  });
  // 请求列表数据
  async function getData() {
    let roleListRes = await reqApi({
      pageNum: paginate.currentPage,
      pageSize: paginate.pageSize,
      ...params,
    });
    if (roleListRes.code === 200) {
      list.value = roleListRes.data.list;
      paginate.total = roleListRes.data.total;
      // console.log(paginate.total);
    }
  }
  getData();

  // 切换启用
  function switchfn(params: number) {
    console.log(params);
  }
  // 分页
  function handleSizeChange(val: number) {
    getData();
  }
  function handleCurrentChange(val: number) {
    getData();
  }
  // 搜索
  function searchfn() {
    getData();
  }

  return {
    list,
    paginate,
    switchfn,
    handleSizeChange,
    handleCurrentChange,
    searchfn,
  };
}
